﻿using UnityEngine;

public class BigGrid:MonoBehaviour
{
    public bool isEmpty
    {
        get
        {
            for (int i = 0; i < 3; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    if (smallGrids[i, j].gridState==GridState.Empty)
                    {
                        return true;
                    }

                }
            }
            return false;
        }
            
    }
    public GridState whoWin
    {
        get
        {
            // Check rows
            for (int i = 0; i < 3; i++)
            {
                if (smallGrids[i, 0].gridState == smallGrids[i, 1].gridState &&
                    smallGrids[i, 1].gridState == smallGrids[i, 2].gridState &&
                    smallGrids[i, 0].gridState != GridState.Empty)
                {
                    return smallGrids[i, 0].gridState;
                }
            }

            // Check columns
            for (int j = 0; j < 3; j++)
            {
                if (smallGrids[0, j].gridState == smallGrids[1, j].gridState &&
                    smallGrids[1, j].gridState == smallGrids[2, j].gridState &&
                    smallGrids[0, j].gridState != GridState.Empty)
                {
                    return smallGrids[0, j].gridState;
                }
            }

            // Check diagonals
            if (smallGrids[0, 0].gridState == smallGrids[1, 1].gridState &&
                smallGrids[1, 1].gridState == smallGrids[2, 2].gridState &&
                smallGrids[0, 0].gridState != GridState.Empty)
            {
                return smallGrids[0, 0].gridState;
            }

            if (smallGrids[0, 2].gridState == smallGrids[1, 1].gridState &&
                smallGrids[1, 1].gridState == smallGrids[2, 0].gridState &&
                smallGrids[0, 2].gridState != GridState.Empty)
            {
                return smallGrids[0, 2].gridState;
            }

            return GridState.Empty;
        }
    }
    public bool canDeploy
    {
        get
        {
            return isEmpty && whoWin == GridState.Empty;
        }
    }

    public SmallGrid[,] smallGrids = new SmallGrid[3,3]; 

    public GridState gridState = GridState.Empty;

    public void CheckState()
    {
        if (whoWin != GridState.Empty)
        {
            GetComponent<SpriteRenderer>().sprite =InputManager.Instance.bigSprites[(int)InputManager.Instance.currentGridState];
            gridState = InputManager.Instance.currentGridState;
            HalfHideSmallGrid();
            MapManager.Instance.CheckState();
        }
        else if (isEmpty == false)
        {
            HalfHideSmallGrid();

        }
    }
    public void HalfHideSmallGrid()
    {
        for (int i = 0; i < 3; i++)
        {
            for (int j = 0; j < 3; j++)
            {
                smallGrids[i, j].GetComponent<SpriteRenderer>().color -= new Color(0, 0, 0, 0.5f);
            }
        }
    }

}
